package com.rjwh.dingdong.client.activity.drawbook;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.BaseActivity;
import com.rjwh.dingdong.client.activity.drawbook.fragment.DrawBookCatalogFragment;
import com.rjwh.dingdong.client.bean.localbean.AgeData;
import com.rjwh.dingdong.client.fragment.BaseFragment;
import com.rjwh.dingdong.client.mvp.presenter.impl.DrawBookCatalogMainActivityPresenter;
import com.rjwh.dingdong.client.mvp.view.DrawBookCatalogMainActivityView;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.view.HackyViewPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author Kay
 * @ClassName DrawBookCatalogMainActivity
 * @Description 绘本馆
 * @date 2016-8-16
 * @history 2016-8-16 author: description:
 */
public class DrawBookCatalogMainActivity extends BaseActivity implements DrawBookCatalogMainActivityView {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @BindView(R.id.loading_layout)
    RelativeLayout loadingLayout;
    @BindView(R.id.error_layout)
    RelativeLayout errorLayout;
    @BindView(R.id.draw_book_catalog_main_viewpager)
    HackyViewPager drawBookCatalogMainViewpager;
    @BindView(R.id.draw_book_catalog_title_btn1)
    Button drawBookCatalogTitleBtn1;
    @BindView(R.id.draw_book_catalog_title_btn2)
    Button drawBookCatalogTitleBtn2;
    @BindView(R.id.draw_book_catalog_tab_root_ll)
    LinearLayout drawBookCatalogTabRootLl;

    private static List<AgeData> ageDatas;
    private List<BaseFragment> listFragment = new ArrayList<>();
    private static MenuItem catalogView;
    private static int pos;
    private int currentAgeID;

    private DrawBookCatalogMainActivityPresenter presenter;
    private int currentItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.draw_book_catalog_main_layout);
        ButterKnife.bind(this);
        ageDatas = new ArrayList<>();
        parseIntent();
        pos = 0;
        initView();
        presenter = new DrawBookCatalogMainActivityPresenter(this, this);
        doGetAge();
    }

    public static void startActivity(Context context, int position) {
        Intent intent = new Intent(context, DrawBookCatalogMainActivity.class);
        intent.putExtra("position", position);
        context.startActivity(intent);
    }

    private void initView() {
        initToolbarHelper();
        DrawBookCatalogFragment catalogFm1 = DrawBookCatalogFragment.getInstance(1);
        DrawBookCatalogFragment catalogFm2 = DrawBookCatalogFragment.getInstance(2);
        listFragment.add(catalogFm1);
        listFragment.add(catalogFm2);
        MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
        drawBookCatalogMainViewpager.setAdapter(adapter);
        drawBookCatalogMainViewpager.addOnPageChangeListener(new HackyViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                updateTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        drawBookCatalogMainViewpager.setCurrentItem(currentItem);
    }

    /**
     * init the toolbar
     */
    protected void initToolbarHelper() {
        toolbar.setTitle("");
        this.setSupportActionBar(this.toolbar);
        getSupportActionBar().setTitle("");
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        drawBookCatalogTabRootLl.setVisibility(View.VISIBLE);
        drawBookCatalogTitleBtn1.setText(getString(R.string.toolbar_drawbook_national));
        drawBookCatalogTitleBtn2.setText(getString(R.string.toolbar_drawbook_level_read));
    }

    private void parseIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            currentItem = intent.getIntExtra("position", 0);
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.getMenuInflater().inflate(R.menu.menu_drawbook_catalog, menu);
        return true;
    }


    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        catalogView = menu.findItem(R.id.menu_catalog_all);// .setIcon(R.drawable.ic_camera);
        catalogView.setVisible(false);
        catalogView.getActionView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onOptionsItemSelected(catalogView);
            }
        });
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_catalog_all:
                showAgeSelectDialog();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 年龄选择框
     */
    private void showAgeSelectDialog() {
        String[] names = new String[0];
        if (ageDatas != null && !ageDatas.isEmpty()) {
            names = new String[ageDatas.size()];
            for (int i = 0; i < ageDatas.size(); i++) {
                names[i] = ageDatas.get(i).getAgename().trim();
            }
        }
        if (names.length > 0) {
            new AlertDialog.Builder(this)
                    .setItems(names, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            if (pos != which) {
                                pos = which;
                                currentAgeID = ageDatas.get(which).getAgecode();
                                LogUtil.e("DrawBookCatalogMainActi", "currentAgeID:" + currentAgeID);
                                currentItem = drawBookCatalogMainViewpager.getCurrentItem();
                                DrawBookCatalogFragment currentFm = (DrawBookCatalogFragment) listFragment.get(currentItem);
                                currentFm.setAgeCode(currentAgeID);
                                currentFm.doRefresh();
                            } else {
                                dialog.dismiss();
                            }
                        }
                    })
                    .show();
        } else {
            new AlertDialog.Builder(this).setMessage("加载失败").show();
        }
    }

    private void doGetAge() {
        presenter.doGetAge();
    }


    @Override
    public void showLoadingView() {
        loadingLayout.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideLoadingView() {
        loadingLayout.setVisibility(View.GONE);
    }

    @Override
    public void showErrorView() {
        errorLayout.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideErrorView() {
        errorLayout.setVisibility(View.GONE);
    }

    @Override
    public void getAge(List<AgeData> agelist) {
        ageDatas = agelist;
        currentAgeID = ageDatas.get(0).getAgecode();
    }

    @Override
    public void setAgeView(boolean isShow) {
        if (catalogView != null) {
            if (isShow) {
                catalogView.setVisible(true);
            } else {
                catalogView.setVisible(false);
            }
        }
    }

    public static void updateAge(boolean isChange) {
        if (isChange) {
            if (ageDatas != null && !ageDatas.isEmpty()) {
                ((TextView) catalogView.getActionView()).setText(ageDatas.get(pos).getAgename().trim());
            }
        }
    }

    /* ***************FragmentPagerAdapter***************** */
    public class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return listFragment.size();
        }

        @Override
        public Fragment getItem(int position) {
            return listFragment.get(position);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return super.isViewFromObject(view, object);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // super.destroyItem(container, position, object);
        }
    }

    @OnClick({R.id.draw_book_catalog_title_btn1, R.id.draw_book_catalog_title_btn2, R.id.btn_refresh})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.draw_book_catalog_title_btn1:
                updateTab(0);
                break;
            case R.id.draw_book_catalog_title_btn2:
                updateTab(1);
                break;
            case R.id.btn_refresh:
                doGetAge();
                break;
        }
    }

    private void updateTab(int position) {
        switch (position) {
            case 0:
                drawBookCatalogTitleBtn1.setClickable(false);
                drawBookCatalogTitleBtn2.setClickable(true);
                drawBookCatalogTitleBtn1.setTextColor(getResources().getColor(R.color.white));
                drawBookCatalogTitleBtn2.setTextColor(getResources().getColor(R.color.blue_button_nor));
                drawBookCatalogTitleBtn1.setBackgroundResource(R.drawable.blue_tab_left_pressed);
                drawBookCatalogTitleBtn2.setBackgroundResource(R.drawable.blue_tab_right_normal);
                //选中的为"国学绘本"
                drawBookCatalogMainViewpager.setCurrentItem(0);
                DrawBookCatalogFragment catalogFragment1 = (DrawBookCatalogFragment) listFragment.get(0);
                int ageCode1 = catalogFragment1.getAgeCode();
                LogUtil.e("DrawBookCatalogMainActi", "ageCode1:" + ageCode1);
                if (ageCode1 != currentAgeID) {
                    catalogFragment1.setAgeCode(currentAgeID);
                    catalogFragment1.doRefresh();
                }
                break;
            case 1:
                drawBookCatalogTitleBtn1.setClickable(true);
                drawBookCatalogTitleBtn2.setClickable(false);
                drawBookCatalogTitleBtn1.setTextColor(getResources().getColor(R.color.blue_button_nor));
                drawBookCatalogTitleBtn2.setTextColor(getResources().getColor(R.color.white));
                drawBookCatalogTitleBtn1.setBackgroundResource(R.drawable.blue_tab_left_normal);
                drawBookCatalogTitleBtn2.setBackgroundResource(R.drawable.blue_tab_right_pressed);
                //选中的为"分级阅读"
                drawBookCatalogMainViewpager.setCurrentItem(1);
                DrawBookCatalogFragment catalogFragment2 = (DrawBookCatalogFragment) listFragment.get(1);
                int ageCode2 = catalogFragment2.getAgeCode();
                LogUtil.e("DrawBookCatalogMainActi", "ageCode2:" + ageCode2);
                if (ageCode2 != currentAgeID) {
                    catalogFragment2.setAgeCode(currentAgeID);
                    catalogFragment2.doRefresh();
                }
                break;

            default:
                break;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.detachView();
    }
}
